package top.archiesean.common.feign.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.http.HttpHeaders;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Enumeration;

/**
 * feign默认使用 的是线程池，也可以更改为信号量也可以解决请求不携带token的问题
 *
 * @author ArchieSean
 * @description 解决feign调用不携带token的问题
 * @date 2024-01-14 08:27
 */
@AutoConfiguration
@RequiredArgsConstructor
public class FeignInterceptor implements RequestInterceptor {


    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null) {
            //1.获取请求对象
            HttpServletRequest request = requestAttributes.getRequest();
            Enumeration<String> headerNames = request.getHeaderNames();
            if (headerNames != null) {
                //2.获取请求对象中的所有的头信息(网关传递过来的)
                while (headerNames.hasMoreElements()) {
                    //头的名称
                    String name = headerNames.nextElement();
                    if (!name.equalsIgnoreCase(HttpHeaders.AUTHORIZATION)) {
                        requestTemplate.header(HttpHeaders.AUTHORIZATION, request.getHeader(name));
                    }
                    // System.out.println("name:" + name + "::::::::value:" + value);
                    //3.将头信息传递给feign (restTemplate)
                }
            }
        }
    }
}
